package com.test.limit;

import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zxs
 * @since 2020/06/29
 */
@Service("funnelLimit")
public class FunnelRateLimiter implements Limiter {
    private final Map<String, Funnel> funnelMap = new HashMap<>();

    @Override
    public boolean isAllow(String key, Integer maxCount, Integer period) {
        Funnel funnel = funnelMap.computeIfAbsent(key, (k) -> new Funnel(maxCount, maxCount / period));
        funnel.makeSpace();
        return funnel.leaking(1);
    }

    static class Funnel {

        private final int capacity;

        private final int leakingRate;

        private int leftQuota;

        private long lastLeakingTs;

        public Funnel(int capacity, int leakingRate) {
            this.capacity = capacity;
            this.leakingRate = leakingRate;
            this.leftQuota = leakingRate;
            lastLeakingTs = System.currentTimeMillis();
        }

        public void makeSpace() {
            long now = System.currentTimeMillis();
            long deltaTs = now - lastLeakingTs;
            int deltaQuota = (int) (deltaTs * leakingRate) / 1000;
            if (deltaQuota < 0) {
                this.leftQuota = capacity;
                this.lastLeakingTs = now;
                return;
            }
            if (deltaQuota < 1) {
                return;
            }
            this.leftQuota += deltaQuota;
            this.lastLeakingTs = now;
            if (this.leftQuota > capacity) {
                this.leftQuota = capacity;
            }
        }

        public boolean leaking(int quota) {
            if (leftQuota >= quota) {
                leftQuota -= quota;
                return true;
            }
            return false;
        }
    }
}
